package cn.py.boot_lua.controller;

import cn.py.boot_lua.dto.SeckillResult;
import cn.py.boot_lua.service.OrderService;
import cn.py.boot_lua.service.SeckillService;
import cn.py.boot_lua.util.RedisUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/seckill")
public class SeckillController {

    private final SeckillService seckillService;
    private final OrderService orderService;
    private final RedisUtil redisUtil;

    public SeckillController(SeckillService seckillService,
                             OrderService orderService,
                             RedisUtil redisUtil) {
        this.seckillService = seckillService;
        this.orderService = orderService;
        this.redisUtil = redisUtil;
    }

    /**
     * 商品提前预热
     * @param productId 商品ID
     * @param stock 库存数量
     */
    @PostMapping("/init/{productId}/{stock}")
    public String initStock(@PathVariable String productId, @PathVariable int stock) {
        String key = "seckill:product:" + productId + ":stock";
        redisUtil.setStock(key, stock, 1, TimeUnit.HOURS);
        return "商品" + productId + "库存初始化完成：" + stock;
    }

    /**
     * 下单
     * @param productId 商品ID
     * @param userId 用户ID
     */
    @PostMapping("/buy/{productId}")
    public ResponseEntity<SeckillResult> buy(@PathVariable String productId, @RequestParam String userId) {
        int result = seckillService.seckill(productId, userId);
        switch (result) {
            case 1:
                orderService.createOrderAsync(productId, userId); // 异步下单
                return ResponseEntity.ok(new SeckillResult(true, "恭喜你秒杀成功！", userId, productId));
            case 0:
                return ResponseEntity.ok(new SeckillResult(false, "库存不足", userId, productId));
            case -1:
                return ResponseEntity.status(500).body(new SeckillResult(false, "库存不存在", userId, productId));
            case -2:
                return ResponseEntity.ok(new SeckillResult(false, "您已抢购过该商品", userId, productId));
            default:
                return ResponseEntity.status(500).body(new SeckillResult(false, "系统异常", userId, productId));
        }
    }
}
